package com.example.farmeri.pojo.vo;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.example.farmeri.tools.ResponseUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Create by weiqishan on 2020/11/7.
 */
public class BaseCallBack implements Callback {

    Handler handler;
    Integer what;

    public BaseCallBack(Handler handler, Integer what) {
        this.handler = handler;
        this.what = what;
    }

    @Override
    public  void onFailure(Call call, IOException e) {
        Log.e("TAG", "网络请求失败");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.code() >= 200  &&  response.code()<=400){
            if (handler == null){
                return;
            }

            ResponseUtils res = (ResponseUtils) JSON.parseObject(response.body().string(),ResponseUtils.class);
            Message msg = Message.obtain();
            if(res.getCode() == 200){
                msg.what = what;
                msg.obj = res.getData();
            }else {
                msg.what = 0x400;
                msg.obj = res.getMessage();
            }
            handler.sendMessage(msg);
        }
    }
}
